package com.zhouk.ams.wx.utils;

import com.zhouk.ams.wx.WxMsg;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create By Zhouke on 2017/10/24
 */
public class WxUtils {
    private static Logger logger = LoggerFactory.getLogger(WxUtils.class);
    /**
     * 排序方法
     *
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);
        StringBuilder sb = new StringBuilder();
        for (String str : strArray) {
            sb.append(str);
        }

        return sb.toString();
    }

    /**
     * 将字符串进行sha1加密
     *
     * @param str 需要加密的字符串
     * @return 加密后的内容
     */
    public static String sha1(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static WxMsg createWxMsg(HttpServletRequest req) throws IOException {
        ServletInputStream input = req.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(input);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elements = root.elements();


        // 遍历所有子节点
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap(6);
        for (Element e : elements) {
            map.put(e.getName(), e.getText());
        }

        // 遍历消息，结果生成WeixinMsg对象
        WxMsg wxMsg = null;
        for (Element e : elements) {
            String toUserName = map.get(WxMsg.TO_USER_NAME);
            String createTime = map.get(WxMsg.CREATE_TIME);
            String fromUserName = map.get(WxMsg.FROM_USER_NAME);
            String msgType = map.get(WxMsg.MSG_TYPE);
            String msgId = map.get(WxMsg.MSG_ID);
            String content = map.get(WxMsg.CONTENT);
            wxMsg = new WxMsg(toUserName, fromUserName, createTime, content, msgType, msgId);

        }
        logger.info("收到消息：{}", wxMsg.toString());
        // 释放资源
        input.close();
        input = null;
        return wxMsg;
    }

    public static String createWxRespMsg(WxMsg wxMsg){
        if (wxMsg == null) {
            return "";
        } else {
            Element root = DocumentHelper.createElement("xml");
            Document document = DocumentHelper.createDocument(root);

            root.addElement(WxMsg.TO_USER_NAME).addCDATA(wxMsg.getFromUserName());
            root.addElement(WxMsg.FROM_USER_NAME).addCDATA(wxMsg.getToUserName());
            root.addElement(WxMsg.CREATE_TIME).addCDATA(String.valueOf(System.currentTimeMillis()).substring(8));
            root.addElement(WxMsg.MSG_TYPE).addCDATA("text");
            root.addElement(WxMsg.CONTENT).addCDATA(wxMsg.getContent());
            String respMsg=document.getRootElement().asXML();
            logger.debug(respMsg);
            return respMsg;
        }
    }
}
